package cn.fz.relaxation.job.douyin;

import cn.fz.relaxation.common.model.dto.HotSearchDetailDTO;
import cn.fz.relaxation.common.util.MyUtil;
import cn.fz.relaxation.dao.entity.RealxHotSearchDO;
import cn.fz.relaxation.service.RelaxHotSearchService;
import cn.fz.relaxation.service.convert.HotSearchConvert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.fz.relaxation.cache.hotSearch.HotSearchCacheManager.CACHE_MAP;
import static cn.fz.relaxation.common.enums.HotSearchEnum.DOUYIN;

@Slf4j
@Component
public class DouyinHotSearchJob {
    @Autowired
    private RelaxHotSearchService relaxHotSearchService;


    public void test() throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url("https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/")
                .method("GET", null)
                .addHeader("accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;"
                                + "q=0.8,application/signed-exchange;v=b3;q=0.7")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("cache-control", "no-cache")
                .addHeader("cookie",
                        "ttwid=1%7CJ6ehEognyMAob_gD6oZwA40monN8E_sENr3IUZmuk7o%7C1712472728"
                                + "%7C44b0cd0003fb75861789d62e56f014eaea3d198898a0ae9a947bf61d95d8ac1a; "
                                + "__ac_signature=_02B4Z6wo00f01fFoqvgAAIDBFmj97SX8qiXxSK5AABr708; "
                                + "__ac_referer=https://pre-dc-console.alibaba-inc.com/; "
                                + "ttwid=1%7CX9ppA_NoTHJI9DG3JN7wNnZ662r-aJbZwCFPLLGK-og%7C1713836331"
                                + "%7Cdbc79a439d0ecc994f60043d66b4ad3ff81c3820f3ab83ef85d30875cc59a18b")
                .addHeader("pragma", "no-cache")
                .addHeader("priority", "u=0, i")
                .addHeader("sec-ch-ua", "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"macOS\"")
                .addHeader("sec-fetch-dest", "document")
                .addHeader("sec-fetch-mode", "navigate")
                .addHeader("sec-fetch-site", "none")
                .addHeader("sec-fetch-user", "?1")
                .addHeader("upgrade-insecure-requests", "1")
                .addHeader("user-agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) "
                                + "Chrome/126.0.0.0 Safari/537.36")
                .build();
        Response response = client.newCall(request).execute();
        if ( ! Objects.isNull(response.body())){
            log.info(JSONObject.toJSONString(response.body().toString()));
        }



    }

    /**
     * 定时触发爬虫方法，1个小时执行一次
     */
    // @Scheduled(fixedRate = 1000 * 60 *60)
    // @Scheduled(fixedRate = 3000)
    @Scheduled(cron = "19 51 10 * * ?")
    public void hotSearch() throws IOException {
        try {
            // 查询抖音热搜数据
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Request request = new Request.Builder().url(
                    "https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/").method("GET", null).build();
            Response response = client.newCall(request).execute();
            assert response.body() != null;
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONArray array = jsonObject.getJSONArray("word_list");
            List<RealxHotSearchDO> searchDOList = Lists.newArrayList();
            for (int i = 0; i < array.size(); i++) {
                // 获取知乎热搜信息
                JSONObject object = (JSONObject)array.get(i);
                // 构建热搜信息榜
                RealxHotSearchDO searchDO = RealxHotSearchDO.builder().hotSearchResource(DOUYIN.getCode()).build();
                // 设置文章标题
                searchDO.setHotSearchTitle(object.getString("word"));
                // 设置知乎三方ID
                searchDO.setHotSearchId(MyUtil.getHashId(DOUYIN.getCode() + searchDO.getHotSearchTitle()));
                // 设置文章连接
                searchDO.setHotSearchUrl("https://www.douyin.com/search/" + searchDO.getHotSearchTitle() + "?type=general");
                // 设置热搜热度
                searchDO.setHotSearchHeat(object.getString("hot_value"));
                // 按顺序排名
                searchDO.setHotSearchOrder(i + 1);
                // 添加到集合
                searchDOList.add(searchDO);
            }
            if (CollectionUtils.isEmpty(searchDOList)){
                log.error("没有获取到抖音数据");
                return;
            }
            // 数据加到缓存中
            CACHE_MAP.put(DOUYIN.getCode(), HotSearchDetailDTO.builder()
                    // 热搜数据
                    .hotSearchDTOList(searchDOList.stream().map(HotSearchConvert::toDTOWhenQuery).collect(Collectors.toList()))
                    // 更新时间
                    .updateTime(Calendar.getInstance().getTime())
                    .build());
            // 数据持久化
            relaxHotSearchService.saveCache2DB(searchDOList);
            log.info("抖音热搜爬虫任务结束");
        } catch (IOException e) {
            log.error("获取抖音数据异常", e);
        }
    }

    public static void main(String[] args) {
        System.out.println(MyUtil.getHashId("当你有一只肥猫就会很显瘦2"));
        System.out.println(MyUtil.getHashId("当你有一只肥猫就会很显瘦2"));
        System.out.println(MyUtil.getHashId("当你有一只肥猫就会很显瘦"));
        System.out.println(MyUtil.getHashId("当你有一只肥猫就会很显瘦"));
    }

    @XxlJob("test666Job")
    public void test666() throws InterruptedException {
        log.info("test666-----------------begin");
        Thread.sleep(2000);
        log.info("test666-----------------end");
    }
}
